package com.study.demo.es;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class EsController {

//    @Bean(name = "client")
    public RestHighLevelClient getRestHighLevelClient() {
        // 阿里云ES集群需要basic auth验证。
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456"));
        RestClientBuilder builder = RestClient.builder(new HttpHost("10.0.0.28", 9200)).setHttpClientConfigCallback(
                new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });
        return new RestHighLevelClient(builder);
    }

//    @Autowired
//    private RestHighLevelClient client;


    /**
     * 地区、品牌、材料、类型、形状，查询条件
     * 价格、时间  排序
     * @throws IOException
     */

    @Test
    public void searchEs() throws IOException {

        RestHighLevelClient client = getRestHighLevelClient();

        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("goods_sell");
        searchRequest.indices("goods_sell");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //地区
        //品牌
        String carBrandCode = "";
        // 材料
        String materialType = "";
        //类型
        String sellType = "";
        //形状
        String energyShape = "1";

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

//        if(StringUtils.isNotEmpty(energyShape)){
//            boolQueryBuilder.filter(QueryBuilders.termQuery("energy_shape",energyShape));
//        }

        searchSourceBuilder.query(boolQueryBuilder);
        //查询数据做冗余，足够后边剔除删除的数据
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(1);
        searchSourceBuilder.sort("create_time", SortOrder.ASC);
        searchSourceBuilder.sort("_doc",SortOrder.ASC);

//        Object[] arrays = new Object[1];
//        arrays[0] = "create_time";
//        searchSourceBuilder.searchAfter();
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));

//        searchRequest.indices("goods_sell").types("_doc");


        searchRequest.source(searchSourceBuilder);

        log.debug("查询语句：{}", searchRequest.toString());

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        log.debug("响应结果：{}", searchResponse.toString());

        if (searchResponse.status() == RestStatus.OK) {
            SearchHits hits = searchResponse.getHits();

            Object[] arrays2 = new Object[1];
            for(SearchHit hit : searchResponse.getHits().getHits()){
                Map<String, Object> map = hit.getSourceAsMap();
                System.out.println(JSONObject.toJSONString(map));
//                System.out.println(hit.getSortValues()[0] + " " + hit.getSortValues()[1]);
                arrays2 = hit.getSortValues();
            }

            log.debug("array:{}",arrays2);

            long totalHits = hits.getTotalHits();

//            Page page = new Page<>(collectDto.getPageNo(), collectDto.getPageSize(), totalHits, idList);


        } else {
//            return Result.buildFailResult("查询收藏信息失败");
        }
    }

    /**
     * 查询单条
     */
//    @Test
    public void testOne() throws IOException {

        RestHighLevelClient client = getRestHighLevelClient();

        String goodsCode = "1023";
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("goods_sell");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //审核通过
        boolQueryBuilder.filter(QueryBuilders.termQuery("goods_code",goodsCode));

        searchSourceBuilder.query(boolQueryBuilder);
        //查询数据做冗余，足够后边剔除删除的数据
        searchSourceBuilder.size(1);
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));

        searchRequest.source(searchSourceBuilder);

        log.debug("查询语句：{}", searchRequest.toString());

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        log.debug("响应结果：{}", searchResponse.toString());

        if (searchResponse.status() == RestStatus.OK) {
            SearchHits hits = searchResponse.getHits();
            SearchHit[] searchHits = hits.getHits();

            Object[] arrays = new Object[1];
            for(SearchHit hit : searchResponse.getHits().getHits()){
                Map<String, Object> map = hit.getSourceAsMap();
                System.out.println(JSONObject.toJSONString(map));
//                System.out.println(hit.getSortValues()[0] + " " + hit.getSortValues()[1]);
                arrays = hit.getSortValues();
            }

            log.debug("array:{}",arrays);

//            GoodsSellVo goodsSellVo = JSON.parseObject(hit.getSourceAsString(), GoodsSellVo.class);

//            log.info("goodsSellVo:{}",JSON.toJSONString(goodsSellVo));
        }
    }
}
